package org.laizili.solution.leetcode;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * <a href="https://leetcode-cn.com/problems/longest-absolute-file-path/">388. 文件的最长绝对路径</a>
 * <p>
 * tags: 栈; 模拟
 */
public class Problem388 {
    private static class Solution {
        public int lengthLongestPath(String input) {
            int res = 0;
            char[] inputArr = input.toCharArray();
            Deque<Integer> dirStack = new ArrayDeque<>();
            for (int i = 0, endIndex; i < inputArr.length; i = endIndex) {
                endIndex = i + 1;
                if (inputArr[i] != '\n') {
                    boolean isDirectory = true;
                    while (endIndex < inputArr.length && inputArr[endIndex] != '\n') {
                        if (inputArr[endIndex] == '.') {
                            isDirectory = false;
                        }
                        endIndex++;
                    }
                    // dir pattern
                    // [字母 数字 空格]+
                    if (isDirectory) dirStack.push(endIndex - i);
                    else {
                        // filename pattern
                        // [字母 数字 空格]+.[字母 数字 空格]+
                        int nLen = endIndex - i;
                        if (!dirStack.isEmpty()) {
                            //nLen += dirStack.stream().reduce(0, Integer::sum, Integer::sum) + dirStack.size();
                            for (Integer sz : dirStack) {
                                nLen += sz;
                            }
                            nLen += dirStack.size();
                        }
                        if (nLen > res) {
                            res = nLen;
                        }
                    }
                } else {
                    // path separator
                    // patten: \n\t*
                    int nestLevel = 0;
                    while (endIndex < inputArr.length && inputArr[endIndex] == '\t') {
                        nestLevel++;
                        endIndex++;
                    }
                    if (nestLevel < dirStack.size()) {
                        while (dirStack.size() != nestLevel) dirStack.pop();
                    }
                }
            }
            return res;
        }
    }

    public static void main(String[] args) {
        // test case
        System.out.println(new Solution().lengthLongestPath("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"));
        System.out.println(new Solution().lengthLongestPath("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"));
        System.out.println(new Solution().lengthLongestPath("a"));
        System.out.println(new Solution().lengthLongestPath("file1.txt\nfile2.txt\nlongfile.txt"));
    }
}
